/*
 * Copyright (C) 2006-2015
 * 版权所有者为北京捷越联合信息咨询有限公司。本系统是商用软件,未经授权擅自复制或传播本程序的部分或全部将是非法的。
 * @title: SendClient.java
 * @package com.jy.modules.cims.component.tbj
 * @author zhaox
 * @date 2015-9-6 上午9:50:34
 * @version v1.00
 * @description: TODO(用一句话描述该文件做什么)
 */

package com.jy.modules.cims.interact;

import java.text.MessageFormat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.open.api.JieYueApiHelper;
import com.jy.modules.cims.common.open.api.dto.ResponseData;
import com.jy.modules.cims.common.open.api.log.InfoLogger;
import com.jy.modules.cims.data.dto.inter.tbj.TBJRequest;
import com.jy.modules.cims.data.dto.inter.tbj.TBJResponse;
import com.jy.modules.platform.sysconfig.service.SysConfigService;


/**
 * @classname: SendClient
 * @description: TODO(这里用一句话描述这个类的作用)
 */
@Service("com.jy.modules.cims.interact.TBJClient")
public class TBJClient {

    private static final Logger logger = LoggerFactory.getLogger(TBJClient.class);

    @Autowired
	@Qualifier("com.jy.modules.platform.sysconfig.service.SysConfigService")
	private SysConfigService sysConfigService;

    int intervalTimes = 3;

    /**
     * 发送请求
     * @title: send
     * @author
     * @description:
     * @date 2015-9-6 上午11:03:00
     * @param tbjRequest
     * @return
     * @throws
     */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private TBJResponse send(TBJRequest tbjRequest) {
		// 密钥，走配置
		JieYueApiHelper helper = getJieYueApiHelperByCooperorgCode(CimsConstant.TBJ_COOPERORG_CODE);
		String serviceURL = sysConfigService.queryValueByCode(MessageFormat.format(SERVICE_URL, CimsConstant.TBJ_COOPERORG_CODE));
		// url，走配置
		ResponseData d = null;
		// 如果不为空同时，为CimsConstant.TBJ_SEND_TYPE_LIST则表示发送list集合
		if (tbjRequest.getType() != null && CimsConstant.TBJ_SEND_TYPE_LIST.equals(tbjRequest.getType())) {
			d = helper.sendRequestForList(serviceURL, tbjRequest.getMethod(), tbjRequest.getContent(), tbjRequest.getClazz());
		} else {
			d = helper.sendRequest(serviceURL, tbjRequest.getMethod(), tbjRequest.getContent(), tbjRequest.getClazz());
		}
		if (d.successVisit() && d.isSign()) {
			Object data = d.getData();
			logger.debug("收到回复信息：" + data);
			TBJResponse tbjResponse = new TBJResponse();
			tbjResponse.setData(data);
			tbjResponse.setMessage(d.getMessage());
			tbjResponse.setRetCode(d.getRetCode());
			if (d.getDataList() != null && d.getDataList().size() > 0) {
				tbjResponse.setDateList(d.getDataList());
			}
			return tbjResponse;
		} else {
			logger.debug("收到异常信息：" + d.getMessage());
			TBJResponse tbjResponse = new TBJResponse();
			tbjResponse.setMessage(d.getMessage());
			tbjResponse.setRetCode(d.getRetCode());
			return tbjResponse;
		}
	}

    /**
     * 异常循环调用
     * 
     * @title: sendInterval
     * @author
     * @description:
     * @date 2015-9-6 下午4:07:10
     * @param tbjRequest
     * @param currentTime
     * @return
     * @throws
     */
    @SuppressWarnings("static-access")
	private TBJResponse sendInterval(TBJRequest tbjRequest, int currentTime) {
        TBJResponse tBJResponse;
        try {
            tBJResponse = this.send(tbjRequest);
            return tBJResponse;
        }
        catch (Exception e) {
            try {
                Thread.currentThread().sleep(1000 * 5);
            }
            catch (InterruptedException e1) {}
            if (currentTime < intervalTimes) {
                sendInterval(tbjRequest, ++currentTime);
            }
        }
        return null;
    }

    /**
     * 供接口调用，将数据发送铜板街
     * 
     * @title: sendToTbj
     * @author
     * @description:
     * @date 2015-9-6 下午4:10:51
     * @param tbjRequest
     * @return
     * @throws
     */
    public TBJResponse sendToTbj(TBJRequest tbjRequest) {
        return this.sendInterval(tbjRequest, 0);
    }
    
    /**
	 * @description 根据机构编码获取API帮助类JieYueApiHelper
	 * @author shengzhoutao
	 * @param cooperorgCode
	 *            机构编码
	 * @return JieYueApiHelper API帮助类
	 */
	public JieYueApiHelper getJieYueApiHelperByCooperorgCode(String cooperorgCode) {
		// 商户为我司提供id
		String appId = sysConfigService.queryValueByCode(MessageFormat.format(SERVICE_APPID, cooperorgCode));
		// 商户服务版本号
		String version = sysConfigService.queryValueByCode(MessageFormat.format(SERVICE_VERSION, cooperorgCode));
		// 商户服务md5key
		String md5key = sysConfigService.queryValueByCode(MessageFormat.format(SERVICE_MD5KEY, cooperorgCode));
		// 商户服务aeskey
		String aesKey = sysConfigService.queryValueByCode(MessageFormat.format(SERVICE_AESKEY, cooperorgCode));

		JieYueApiHelper helper = new JieYueApiHelper(new InfoLogger(JieYueApiHelper.class), md5key, aesKey, "UTF-8", null, appId, version);

		return helper;
	}
	
	private final String SERVICE_APPID = "{0}.service.appid";// 商户id
	private final String SERVICE_URL = "{0}.service.url";// 商户服务端地址
	private final String SERVICE_VERSION = "{0}.service.version";// 商户服务版本号
	private final String SERVICE_MD5KEY = "{0}.service.md5key";// 商户服务md5key
	private final String SERVICE_AESKEY = "{0}.service.aeskey";// 商户服务aeskey

}
